<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/dxl/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/dxl/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/dxl/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/dxl/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/dxl/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/dxl/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/dxl/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/dxl/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/dxl/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Django,">










<meta name="description" content="一、会话跟踪技术1、定义：     ​            在一个会话的多个请求中共享数据，这就是会话跟踪技术 2、可以通过哪些方式实现 ​            cookie、 session 二、cookie1、产生背景 ​        http协议没有状态：对服务器来说，每次的请求都是全新的 2、什么是cookie ​        cookie是浏览器的技术，Cookie具体指的是一段">
<meta name="keywords" content="Django">
<meta property="og:type" content="article">
<meta property="og:title" content="CooKies和Session">
<meta property="og:url" content="http://yoursite.com/2019/09/21/【Django】08cookie和session - 副本/index.html">
<meta property="og:site_name" content="我的快乐时光">
<meta property="og:description" content="一、会话跟踪技术1、定义：     ​            在一个会话的多个请求中共享数据，这就是会话跟踪技术 2、可以通过哪些方式实现 ​            cookie、 session 二、cookie1、产生背景 ​        http协议没有状态：对服务器来说，每次的请求都是全新的 2、什么是cookie ​        cookie是浏览器的技术，Cookie具体指的是一段">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2019/09/21/【Django】08cookie和session%20-%20副本/assets/1567315855292.png">
<meta property="og:image" content="http://yoursite.com/2019/09/21/【Django】08cookie和session%20-%20副本/assets/1567315882283.png">
<meta property="og:image" content="http://yoursite.com/2019/09/21/【Django】08cookie和session%20-%20副本/assets/1567317158760.png">
<meta property="og:image" content="http://yoursite.com/2019/09/21/【Django】08cookie和session%20-%20副本/assets/1567317571505.png">
<meta property="og:updated_time" content="2019-09-21T07:27:12.441Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="CooKies和Session">
<meta name="twitter:description" content="一、会话跟踪技术1、定义：     ​            在一个会话的多个请求中共享数据，这就是会话跟踪技术 2、可以通过哪些方式实现 ​            cookie、 session 二、cookie1、产生背景 ​        http协议没有状态：对服务器来说，每次的请求都是全新的 2、什么是cookie ​        cookie是浏览器的技术，Cookie具体指的是一段">
<meta name="twitter:image" content="http://yoursite.com/2019/09/21/【Django】08cookie和session%20-%20副本/assets/1567315855292.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/dxl/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/09/21/【Django】08cookie和session - 副本/">





  <title>CooKies和Session | 我的快乐时光</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/dxl/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的快乐时光</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/dxl/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/dxl/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/dxl/2019/09/21/【Django】08cookie和session - 副本/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content>
      <meta itemprop="description" content>
      <meta itemprop="image" content="/dxl/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的快乐时光">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">CooKies和Session</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-21T15:24:35+08:00">
                2019-09-21
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/dxl/categories/Django/" itemprop="url" rel="index">
                    <span itemprop="name">Django</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/dxl/2019/09/21/【Django】08cookie和session - 副本/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/dxl/2019/09/21/【Django】08cookie和session - 副本/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="一、会话跟踪技术"><a href="#一、会话跟踪技术" class="headerlink" title="一、会话跟踪技术"></a>一、会话跟踪技术</h2><p>1、定义：    </p>
<p>​            在一个会话的多个请求中共享数据，这就是会话跟踪技术</p>
<p>2、可以通过哪些方式实现</p>
<p>​            cookie、 session</p>
<h2 id="二、cookie"><a href="#二、cookie" class="headerlink" title="二、cookie"></a>二、cookie</h2><p>1、产生背景</p>
<p>​        http协议没有状态：对服务器来说，每次的请求都是全新的</p>
<p>2、什么是cookie</p>
<p>​        cookie是浏览器的技术，Cookie具体指的是一段小信息，它是服务器发送出来存储在浏 览器上的一组组键值对，下次访问服务器时浏览器会自动携带这些键值对，以便服务器提取有用信息。</p>
<p>3、cookie原理</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、浏览器访问服务端，带着一个空的cookie</span><br><span class="line"><span class="number">2</span>、服务器产生内容放入cookie，发送给客户端</span><br><span class="line"><span class="number">3</span>、浏览器下次访问，自动携带cookie</span><br><span class="line"><span class="number">4</span>、服务器提取cookie数据进行数据判断</span><br></pre></td></tr></table></figure>

<p>4、查看cookie</p>
<p><img src="assets/1567315855292.png" alt="1567315855292"></p>
<p>5、图解</p>
<p><img src="assets/1567315882283.png" alt="1567315882283"></p>
<p>6、cookie规范</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、Cookie大小上限为<span class="number">4</span>KB； </span><br><span class="line"><span class="number">2</span>、一个服务器最多在客户端浏览器上保存<span class="number">20</span>个Cookie； </span><br><span class="line"><span class="number">3</span>、一个浏览器最多保存<span class="number">300</span>个Cookie，因为一个浏览器可以访问多个服务器。</span><br><span class="line">注意事项：</span><br><span class="line"><span class="number">1</span>、随着科技的进步:每个Cookie的大小为<span class="number">8</span>KB，最多可保存<span class="number">500</span>个Cookie</span><br><span class="line"><span class="number">2</span>、不同浏览器之间是不共享Cookie的</span><br></pre></td></tr></table></figure>

<p>7、Cookie与HTTP头  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Cookie是通过HTTP请求和响应头在客户端和服务器端传递的</span><br></pre></td></tr></table></figure>

<p>8、Cookie的覆盖 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">如果服务器端发送重复的Cookie那么会覆盖原有的Cookie</span><br><span class="line">eg:</span><br><span class="line">1、客户端的第一个请求服务器端发送的Cookie是：Set-Cookie: a=A；</span><br><span class="line">2、第二请求服务器端发送的是：Set-Cookie: a=AA</span><br><span class="line">3、客户端只留下一个Cookie，即：a=AA。</span><br></pre></td></tr></table></figure>

<h2 id="三、django操作cookie"><a href="#三、django操作cookie" class="headerlink" title="三、django操作cookie"></a>三、django操作cookie</h2><h3 id="3-1、清除页面缓存"><a href="#3-1、清除页面缓存" class="headerlink" title="3.1、清除页面缓存"></a>3.1、清除页面缓存</h3><p>​            Ctrl + Shift + del三个键来清除页面缓存和cookie</p>
<h3 id="3-2、获取cookie"><a href="#3-2、获取cookie" class="headerlink" title="3.2、获取cookie"></a>3.2、获取cookie</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">request.COOKIES[<span class="string">'key'</span>]</span><br><span class="line">request.get_signed_cookie(key, default=RAISE_ERROR, salt=<span class="string">''</span>, max_age=<span class="literal">None</span>)</span><br><span class="line">参数解释：</span><br><span class="line">	default: 默认值</span><br><span class="line">　　　　　　salt: 加密盐</span><br><span class="line">　　　　　　max_age: 后台控制过期时间</span><br></pre></td></tr></table></figure>

<h3 id="3-3、设置cookie"><a href="#3-3、设置cookie" class="headerlink" title="3.3、设置cookie"></a>3.3、设置cookie</h3><p>1、设置cookie</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">rep = HttpResponse(...)</span><br><span class="line">rep ＝ render(request, ...)</span><br><span class="line">rep.set_cookie(key,value,...)</span><br><span class="line">rep.set_signed_cookie(key,value,salt=<span class="string">'加密盐'</span>, max_age=<span class="literal">None</span>, ...)</span><br><span class="line">参数：</span><br><span class="line">　　　　　　key, 键</span><br><span class="line">　　　　　　value=<span class="string">''</span>, 值</span><br><span class="line">　　　　　　max_age=<span class="literal">None</span>, 超时时间</span><br><span class="line">　　　　　　expires=<span class="literal">None</span>, 超时时间(IE requires expires, so set it <span class="keyword">if</span> hasn<span class="string">'t been already.)</span></span><br><span class="line"><span class="string">　　　　　　path='</span>/<span class="string">', Cookie生效的路径，/ 表示根路径，特殊的：根路径的cookie可以被任何url的页面访问</span></span><br><span class="line"><span class="string">　　　　　　domain=None, Cookie生效的域名</span></span><br><span class="line"><span class="string">　　　　　　secure=False, https传输</span></span><br><span class="line"><span class="string">　　　　　　httponly=False 只能http协议传输，无法被JavaScript获取（不是绝对，底层抓包可以获取到也可以被覆盖）</span></span><br></pre></td></tr></table></figure>

<p>2、源码展示</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">class HttpResponseBase:</span><br><span class="line"></span><br><span class="line">        def set_cookie(self, key,                 键</span><br><span class="line">        　　　　　　　　　　　　 value=&apos;&apos;,            值</span><br><span class="line">        　　　　　　　　　　　　 max_age=None,        超长时间 ,有效事件，max_age=20意思是这个cookie20秒后就消失了，默认时长是2周,这个是以秒为单位的</span><br><span class="line">　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　cookie需要延续的时间（以秒为单位）</span><br><span class="line">　　　　　　　　　　　　　　　　　　　　　　　　　　　　　　如果参数是\ None`` ，这个cookie会延续到浏览器关闭为止。</span><br><span class="line"></span><br><span class="line">        　　　　　　　　　　　　 expires=None,        超长时间，值是一个datetime类型的时间日期对象，到这个日期就失效的意思，用的不多</span><br><span class="line">       　　　　　　　　　　　　　　　　　　　　　　　　　　expires默认None ,cookie失效的实际日期/时间。 </span><br><span class="line">    　　　　　　　　　　　　　　　　　　　　　　　　　　　　</span><br><span class="line"></span><br><span class="line">        　　　　　　　　　　　　 path=&apos;/&apos;,           Cookie生效的路径，就是访问哪个路径可以得到cookie，&apos;/&apos;是所有路径都能获得cookie</span><br><span class="line">                                                 浏览器只会把cookie回传给带有该路径的页面，这样可以避免将</span><br><span class="line">                                                 cookie传给站点中的其他的应用。</span><br><span class="line">                                                 / 表示根路径，特殊的：根路径的cookie可以被任何url的页面访问</span><br><span class="line">        　　　　　　　　　　　　 </span><br><span class="line">                             domain=None,         Cookie生效的域名</span><br><span class="line">                                                </span><br><span class="line">                                                  你可用这个参数来构造一个跨站cookie。</span><br><span class="line">                                                  如， domain=&quot;.example.com&quot;</span><br><span class="line">                                                  所构造的cookie对下面这些站点都是可读的：</span><br><span class="line">                                                  www.example.com 、 www2.example.com </span><br><span class="line">        　　　　　　　　　　　　　　　　　　　　　　　　　和an.other.sub.domain.example.com 。</span><br><span class="line">                                                  如果该参数设置为 None ，cookie只能由设置它的站点读取。</span><br><span class="line"></span><br><span class="line">        　　　　　　　　　　　　 secure=False,        如果设置为 True ，浏览器将通过HTTPS来回传cookie。</span><br><span class="line">        　　　　　　　　　　　　 httponly=False       只能http协议传输，无法被JavaScript获取</span><br><span class="line">                                                 （不是绝对，底层抓包可以获取到也可以被覆盖）</span><br><span class="line">        　　　　　　　　　　): pass</span><br></pre></td></tr></table></figure>

<h3 id="3-4删除cookie"><a href="#3-4删除cookie" class="headerlink" title="3.4删除cookie"></a>3.4删除cookie</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">logout</span><span class="params">(request)</span>:</span></span><br><span class="line">    rep = redirect(<span class="string">"/login/"</span>)</span><br><span class="line">    rep.delete_cookie(<span class="string">"user"</span>)  <span class="comment"># 删除用户浏览器上之前设置的usercookie值</span></span><br><span class="line">    <span class="keyword">return</span> rep</span><br></pre></td></tr></table></figure>

<h3 id="3-5Cookie版登陆校验示例"><a href="#3-5Cookie版登陆校验示例" class="headerlink" title="3.5Cookie版登陆校验示例"></a>3.5Cookie版登陆校验示例</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">check_login</span><span class="params">(func)</span>:</span></span><br><span class="line"><span class="meta">    @wraps(func)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">inner</span><span class="params">(request, *args, **kwargs)</span>:</span></span><br><span class="line">        next_url = request.get_full_path()</span><br><span class="line">        <span class="keyword">if</span> request.get_signed_cookie(<span class="string">"login"</span>, salt=<span class="string">"SSS"</span>, default=<span class="literal">None</span>) == <span class="string">"yes"</span>:</span><br><span class="line">            <span class="comment"># 已经登录的用户...</span></span><br><span class="line">            <span class="keyword">return</span> func(request, *args, **kwargs)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 没有登录的用户，跳转刚到登录页面</span></span><br><span class="line">            <span class="keyword">return</span> redirect(<span class="string">"/login/?next=&#123;&#125;"</span>.format(next_url))</span><br><span class="line">    <span class="keyword">return</span> inner</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">login</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">"POST"</span>:</span><br><span class="line">        username = request.POST.get(<span class="string">"username"</span>)</span><br><span class="line">        passwd = request.POST.get(<span class="string">"password"</span>)</span><br><span class="line">        <span class="keyword">if</span> username == <span class="string">"xxx"</span> <span class="keyword">and</span> passwd == <span class="string">"dashabi"</span>:</span><br><span class="line">            next_url = request.GET.get(<span class="string">"next"</span>)</span><br><span class="line">            <span class="keyword">if</span> next_url <span class="keyword">and</span> next_url != <span class="string">"/logout/"</span>:</span><br><span class="line">                response = redirect(next_url)</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                response = redirect(<span class="string">"/class_list/"</span>)</span><br><span class="line">            response.set_signed_cookie(<span class="string">"login"</span>, <span class="string">"yes"</span>, salt=<span class="string">"SSS"</span>)</span><br><span class="line">            <span class="keyword">return</span> response</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">"login.html"</span>)</span><br></pre></td></tr></table></figure>

<h3 id="3-6-cookie中的中文解决方案"><a href="#3-6-cookie中的中文解决方案" class="headerlink" title="3.6 cookie中的中文解决方案"></a>3.6 cookie中的中文解决方案</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"># 方式1</span><br><span class="line">def login(request):</span><br><span class="line"></span><br><span class="line">    ret = HttpResponse(&apos;ok&apos;)</span><br><span class="line">    </span><br><span class="line">    ret.set_cookie(&apos;k1&apos;,&apos;你好&apos;.encode(&apos;utf-8&apos;).decode(&apos;iso-8859-1&apos;))</span><br><span class="line">    </span><br><span class="line">    #取值：request.COOKIES[&apos;k1&apos;].encode(&apos;utf-8&apos;).decode(&apos;iso-8859-1&apos;).encode(&apos;iso-8859-1&apos;).decode(&apos;utf-8&apos;)</span><br><span class="line"></span><br><span class="line">    return ret</span><br><span class="line"></span><br><span class="line">方式2 json</span><br><span class="line"></span><br><span class="line">def login(request):</span><br><span class="line"></span><br><span class="line">    ret = HttpResponse(&apos;ok&apos;)</span><br><span class="line">    </span><br><span class="line">    import json</span><br><span class="line"></span><br><span class="line">    ret.set_cookie(&apos;k1&apos;,json.dumps(&apos;你好&apos;))</span><br><span class="line">    #取值 json.loads(request.COOKIES[&apos;k1&apos;])</span><br><span class="line">    return ret</span><br></pre></td></tr></table></figure>

<h3 id="3-7-可以实现那些功能"><a href="#3-7-可以实现那些功能" class="headerlink" title="3.7 可以实现那些功能"></a>3.7 可以实现那些功能</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1、显示上次访问时间。　</span><br><span class="line">2、显示上次浏览过的商品。</span><br><span class="line">个人建议使用数据库进行存储，因为用户可以使用不同的app进行登录</span><br></pre></td></tr></table></figure>

<h2 id="四、session"><a href="#四、session" class="headerlink" title="四、session"></a>四、session</h2><p>1、什么是session</p>
<p>​         Session是服务器端技术，利用这个技术，服务器在运行时可以 为每一个用户的浏览器创建一个其独享的session对象，由于 session为用户浏览器独享，所以用户在访问服务器的web资源时 ，可以把各自的数据放在各自的session中，当用户再去访问该服务器中的其它web资源时，其它web资源再从用户各自的session中 取出数据为用户服务。</p>
<p><img src="assets/1567317158760.png" alt="1567317158760"></p>
<p>2、和cook相比的优势</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1、保存在服务器更加安全</span><br><span class="line">2、保存的私密信息文本超过4096个字节</span><br></pre></td></tr></table></figure>

<h2 id="五、djanjo操作session"><a href="#五、djanjo操作session" class="headerlink" title="五、djanjo操作session"></a>五、djanjo操作session</h2><h3 id="5-1相关操作方法"><a href="#5-1相关操作方法" class="headerlink" title="5.1相关操作方法"></a>5.1相关操作方法</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">　　注意：这都是django提供的方法，其他的框架就需要你自己关于cookie和session的方法了。</span><br><span class="line"><span class="comment"># 获取、设置、删除Session中数据</span></span><br><span class="line"><span class="comment">#取值</span></span><br><span class="line">request.session[<span class="string">'k1'</span>] </span><br><span class="line">request.session.get(<span class="string">'k1'</span>,<span class="literal">None</span>) </span><br><span class="line"><span class="comment">#1、request.session这句是帮你从cookie里面将sessionid的值取出来，</span></span><br><span class="line"><span class="comment">#2、sessionid的值的那条记录中的session-data字段的数据给你拿出来（并解密）,</span></span><br><span class="line"><span class="comment">#3、get方法就取出k1这个键对应的值</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#设置值</span></span><br><span class="line">request.session[<span class="string">'k1'</span>] = <span class="number">123</span></span><br><span class="line">request.session.setdefault(<span class="string">'k1'</span>,<span class="number">123</span>) </span><br><span class="line"><span class="comment">#1、存在则不设置</span></span><br><span class="line"><span class="comment">#2、帮你生成随机字符串，帮你将这个随机字符串和用户数据（加密后）,和过期时间保存到了django-session表里面，帮你将这个随机字符串以sessionid：</span></span><br><span class="line"><span class="comment">#3、随机字符串的形式添加到cookie里面返回给浏览器,这个sessionid名字是可以改的，以后再说</span></span><br><span class="line"><span class="comment">#4、但是注意一个事情，django-session这个表，你不能通过orm来直接控制，</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#删除值</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">del</span> request.session[<span class="string">'k1'</span>]  <span class="comment">#django-session表里面同步删除</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 所有 键、值、键值对</span></span><br><span class="line">request.session.keys()</span><br><span class="line">request.session.values()</span><br><span class="line">request.session.items()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 会话session的key</span></span><br><span class="line">session_key = request.session.session_key  获取sessionid的值</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将所有Session失效日期小于当前日期的数据删除，将过期的删除</span></span><br><span class="line">request.session.clear_expired()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 检查会话session的key在数据库中是否存在</span></span><br><span class="line">request.session.exists(<span class="string">"session_key"</span>) </span><br><span class="line"><span class="comment">#session_key就是那个sessionid的值</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 删除当前会话的所有Session数据</span></span><br><span class="line">request.session.delete()</span><br><span class="line">　　</span><br><span class="line"><span class="comment"># 删除当前的会话数据并删除会话的Cookie。</span></span><br><span class="line">request.session.flush()  </span><br><span class="line"><span class="comment">#常用，清空所有cookie---删除session表里的这个会话的记录，</span></span><br><span class="line">    这用于确保前面的会话数据不可以再次被用户的浏览器访问</span><br><span class="line">    例如，django.contrib.auth.logout() 函数中就会调用它。</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置会话Session和Cookie的超时时间</span></span><br><span class="line">request.session.set_expiry(value)</span><br><span class="line">    * 如果value是个整数，session会在些秒数后失效。</span><br><span class="line">    * 如果value是个datatime或timedelta，session就会在这个时间后失效。</span><br><span class="line">    * 如果value是<span class="number">0</span>,用户关闭浏览器session就会失效。</span><br><span class="line">    * 如果value是<span class="literal">None</span>,session会依赖全局session失效策略。</span><br></pre></td></tr></table></figure>

<h3 id="5-2图解"><a href="#5-2图解" class="headerlink" title="5.2图解"></a>5.2图解</h3><p><img src="assets/1567317571505.png" alt="1567317571505"></p>
<h3 id="5-3session版登录验证实例"><a href="#5-3session版登录验证实例" class="headerlink" title="5.3session版登录验证实例"></a>5.3session版登录验证实例</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> wraps</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">check_login</span><span class="params">(func)</span>:</span></span><br><span class="line"><span class="meta">    @wraps(func)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">inner</span><span class="params">(request, *args, **kwargs)</span>:</span></span><br><span class="line">        next_url = request.get_full_path()</span><br><span class="line">        <span class="keyword">if</span> request.session.get(<span class="string">"user"</span>):</span><br><span class="line">            <span class="keyword">return</span> func(request, *args, **kwargs)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> redirect(<span class="string">"/login/?next=&#123;&#125;"</span>.format(next_url))</span><br><span class="line">    <span class="keyword">return</span> inner</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">login</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">"POST"</span>:</span><br><span class="line">        user = request.POST.get(<span class="string">"user"</span>)</span><br><span class="line">        pwd = request.POST.get(<span class="string">"pwd"</span>)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> user == <span class="string">"dxldxl"</span> <span class="keyword">and</span> pwd == <span class="string">"1234"</span>:</span><br><span class="line">            <span class="comment"># 设置session</span></span><br><span class="line">            request.session[<span class="string">"user"</span>] = user</span><br><span class="line">            <span class="comment"># 获取跳到登陆页面之前的URL</span></span><br><span class="line">            next_url = request.GET.get(<span class="string">"next"</span>)</span><br><span class="line">            <span class="comment"># 如果有，就跳转回登陆之前的URL</span></span><br><span class="line">            <span class="keyword">if</span> next_url:</span><br><span class="line">                <span class="keyword">return</span> redirect(next_url)</span><br><span class="line">            <span class="comment"># 否则默认跳转到index页面</span></span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">return</span> redirect(<span class="string">"/index/"</span>)</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">"login.html"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@check_login</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">logout</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="comment"># 删除所有当前请求相关的session</span></span><br><span class="line">    request.session.delete()</span><br><span class="line">    <span class="keyword">return</span> redirect(<span class="string">"/login/"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@check_login</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span></span><br><span class="line">    current_user = request.session.get(<span class="string">"user"</span>, <span class="literal">None</span>)</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">"index.html"</span>, &#123;<span class="string">"user"</span>: current_user&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="5-4session的进一步理解"><a href="#5-4session的进一步理解" class="headerlink" title="5.4session的进一步理解"></a>5.4session的进一步理解</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">一个浏览器和一个网站能保持两个用户的对话吗？</span><br><span class="line">不可以：</span><br><span class="line">1、第一个用户登陆的时候，没有带着sessionid</span><br><span class="line">2、第二个用户登陆的时候，带着第一个用户的sessionid，这个值在第二个用户登陆之后，session就被覆盖了，浏览器上的sessionid就是我第二个用户的了，</span><br><span class="line">3、那么你用第一个用户再点击其他内容，你会发现，看到的都是第二个用户的信息（注意：公众都能访问的a标签不算）</span><br></pre></td></tr></table></figure>

<h3 id="5-5Django中的session设置"><a href="#5-5Django中的session设置" class="headerlink" title="5.5Django中的session设置"></a>5.5Django中的session设置</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 数据库Session</span><br><span class="line">SESSION_ENGINE = <span class="string">'django.contrib.sessions.backends.db'</span>   <span class="comment"># 引擎（默认）</span></span><br><span class="line"></span><br><span class="line"><span class="number">2.</span> 缓存Session</span><br><span class="line">SESSION_ENGINE = <span class="string">'django.contrib.sessions.backends.cache'</span>  <span class="comment"># 引擎</span></span><br><span class="line">SESSION_CACHE_ALIAS = <span class="string">'default'</span>                            <span class="comment"># 使用的缓存别名（默认内存缓存，也可以是memcache），此处别名依赖缓存的设置</span></span><br><span class="line"></span><br><span class="line"><span class="number">3.</span> 文件Session</span><br><span class="line">SESSION_ENGINE = <span class="string">'django.contrib.sessions.backends.file'</span>    <span class="comment"># 引擎</span></span><br><span class="line">SESSION_FILE_PATH = <span class="literal">None</span>                                    <span class="comment"># 缓存文件路径，如果为None，则使用tempfile模块获取一个临时地址tempfile.gettempdir() </span></span><br><span class="line"></span><br><span class="line"><span class="number">4.</span> 缓存+数据库</span><br><span class="line">SESSION_ENGINE = <span class="string">'django.contrib.sessions.backends.cached_db'</span>        <span class="comment"># 引擎</span></span><br><span class="line"></span><br><span class="line"><span class="number">5.</span> 加密Cookie Session</span><br><span class="line">SESSION_ENGINE = <span class="string">'django.contrib.sessions.backends.signed_cookies'</span>   <span class="comment"># 引擎</span></span><br><span class="line"></span><br><span class="line">其他公用设置项：</span><br><span class="line">SESSION_COOKIE_NAME ＝ <span class="string">"sessionid"</span>                       <span class="comment"># Session的cookie保存在浏览器上时的key，即：sessionid＝随机字符串（默认）</span></span><br><span class="line">SESSION_COOKIE_PATH ＝ <span class="string">"/"</span>                               <span class="comment"># Session的cookie保存的路径（默认）</span></span><br><span class="line">SESSION_COOKIE_DOMAIN = <span class="literal">None</span>                             <span class="comment"># Session的cookie保存的域名（默认）</span></span><br><span class="line">SESSION_COOKIE_SECURE = <span class="literal">False</span>                            <span class="comment"># 是否Https传输cookie（默认）</span></span><br><span class="line">SESSION_COOKIE_HTTPONLY = <span class="literal">True</span>                           <span class="comment"># 是否Session的cookie只支持http传输（默认）</span></span><br><span class="line">SESSION_COOKIE_AGE = <span class="number">1209600</span>                             <span class="comment"># Session的cookie失效日期（2周）（默认）</span></span><br><span class="line">SESSION_EXPIRE_AT_BROWSER_CLOSE = <span class="literal">False</span>                  <span class="comment"># 是否关闭浏览器使得Session过期（默认）</span></span><br><span class="line">SESSION_SAVE_EVERY_REQUEST = <span class="literal">False</span>                       <span class="comment"># 是否每次请求都保存Session，默认修改之后才保存（默认）</span></span><br></pre></td></tr></table></figure>

<h2 id="六-CSRF-Token装饰器"><a href="#六-CSRF-Token装饰器" class="headerlink" title="六 CSRF Token装饰器"></a>六 CSRF Token装饰器</h2><p>​            CSRF Token相关装饰器在CBV只能加到dispatch方法上，或者加在视图类上然后name参数指定为dispatch方法。</p>
<p>备注：</p>
<p>​        csrf_protect，为当前函数强制设置防跨站请求伪造功能，即便settings中没有设置全局中间件。</p>
<p>​        csrf_exempt，取消当前函数防跨站请求伪造功能，即便settings中设置了全局中间件。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.views.decorators.csrf <span class="keyword">import</span> csrf_exempt, csrf_protect</span><br><span class="line"><span class="keyword">from</span> django.utils.decorators <span class="keyword">import</span> method_decorator</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HomeView</span><span class="params">(View)</span>:</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @method_decorator(csrf_exempt)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">dispatch</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> super(HomeView, self).dispatch(request, *args, **kwargs)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> render(request, <span class="string">"home.html"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        print(<span class="string">"Home View POST method..."</span>)</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">"/index/"</span>)</span><br><span class="line"><span class="keyword">from</span> django.views.decorators.csrf <span class="keyword">import</span> csrf_exempt, csrf_protect</span><br><span class="line"><span class="keyword">from</span> django.utils.decorators <span class="keyword">import</span> method_decorator</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@method_decorator(csrf_exempt, name='dispatch')</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">HomeView</span><span class="params">(View)</span>:</span></span><br><span class="line">   </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">dispatch</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> super(HomeView, self).dispatch(request, *args, **kwargs)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> render(request, <span class="string">"home.html"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        print(<span class="string">"Home View POST method..."</span>)</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">"/index/"</span>)</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://yoursite.com/2019/09/21/【Django】08cookie和session - 副本/" title="CooKies和Session">http://yoursite.com/2019/09/21/【Django】08cookie和session - 副本/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/dxl/tags/Django/" rel="tag"># Django</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/dxl/2019/09/21/【Django】03视图函数 - 副本/" rel="next" title="视图函数">
                <i class="fa fa-chevron-left"></i> 视图函数
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/dxl/2019/10/09/【面试题】04-3权限模式 - 副本 - 副本/" rel="prev" title="权限复习">
                权限复习 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/dxl/images/avatar.png" alt>
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/dxl/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/dxl/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/dxl/tags/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-sign-out"></i>
                我的友链
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="tencent://message/?Menu=yes&uin=1258517737&Site=QQ%E6%9E%81%E5%AE%A2&Service=300&sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45/" title="申请坑位" target="_blank">申请坑位</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、会话跟踪技术"><span class="nav-number">1.</span> <span class="nav-text">一、会话跟踪技术</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、cookie"><span class="nav-number">2.</span> <span class="nav-text">二、cookie</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、django操作cookie"><span class="nav-number">3.</span> <span class="nav-text">三、django操作cookie</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1、清除页面缓存"><span class="nav-number">3.1.</span> <span class="nav-text">3.1、清除页面缓存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2、获取cookie"><span class="nav-number">3.2.</span> <span class="nav-text">3.2、获取cookie</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3、设置cookie"><span class="nav-number">3.3.</span> <span class="nav-text">3.3、设置cookie</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4删除cookie"><span class="nav-number">3.4.</span> <span class="nav-text">3.4删除cookie</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-5Cookie版登陆校验示例"><span class="nav-number">3.5.</span> <span class="nav-text">3.5Cookie版登陆校验示例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-6-cookie中的中文解决方案"><span class="nav-number">3.6.</span> <span class="nav-text">3.6 cookie中的中文解决方案</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-7-可以实现那些功能"><span class="nav-number">3.7.</span> <span class="nav-text">3.7 可以实现那些功能</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、session"><span class="nav-number">4.</span> <span class="nav-text">四、session</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、djanjo操作session"><span class="nav-number">5.</span> <span class="nav-text">五、djanjo操作session</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1相关操作方法"><span class="nav-number">5.1.</span> <span class="nav-text">5.1相关操作方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2图解"><span class="nav-number">5.2.</span> <span class="nav-text">5.2图解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3session版登录验证实例"><span class="nav-number">5.3.</span> <span class="nav-text">5.3session版登录验证实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-4session的进一步理解"><span class="nav-number">5.4.</span> <span class="nav-text">5.4session的进一步理解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-5Django中的session设置"><span class="nav-number">5.5.</span> <span class="nav-text">5.5Django中的session设置</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六-CSRF-Token装饰器"><span class="nav-number">6.</span> <span class="nav-text">六 CSRF Token装饰器</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-hand-peace-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder"></span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/dxl/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/dxl/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/dxl/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/dxl/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/dxl/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/dxl/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '13B0JGDuA6ttduN8AQaR8CzF-gzGzoHsz',
        appKey: 'I13r9r5mVgq4jQYpYy6V4gW3',
        placeholder: '欢迎大佬指点~~~',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
